package cc.angis.xiugallery;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.data.FolderData;
import cc.angis.xiugallery.db.FavouriteDBHelper;
import cc.angis.xiugallery.db.FavouriteImagesDBHelper;
import cc.angis.xiugallery.db.TableConstants;
import cc.angis.xiugallery.image.ui.ImageGridActivity;
import cc.angis.xiugallery.image.util.ImageCache;
import cc.angis.xiugallery.image.util.ImageCache.ImageCacheParams;
import cc.angis.xiugallery.image.util.ImageResizer;
import cc.angis.xiugallery.image.util.ThumbnailImageLoader;
import cc.angis.xiugallery.image.util.Utils;
import cc.angis.xiugallery.provider.FavouriteGalleryProvider;
import cc.angis.xiugallery.provider.IFolderSourceProvider;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class FavouriteGridFragment extends SherlockFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    private static final String TAG = "FavouriteGridFragment";
    private static final String IMAGE_CACHE_DIR = "thumbs";
    private int mFolderThumbSize;
    private int mImageThumbSize;
    private int mFolderThumbSpacing;
    private GroupingAdapter mAdapter;
    private IFolderSourceProvider mSourceProvider;
//    private Handler imageHandler;
    private ImageResizer mImageWorker;
    
    private GridView mGridView;
    
    private List<String> mDeletedFavs;
    
    /**
     * Empty constructor as per the Fragment documentation
     */
    public FavouriteGridFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.folder_thumbnail_size);
        mFolderThumbSize = getResources().getDimensionPixelSize(R.dimen.folder_thumbnail_size);
        mFolderThumbSpacing = getResources().getDimensionPixelSize(R.dimen.folder_thumbnail_spacing);
        mSourceProvider = new FavouriteGalleryProvider(getActivity());
        mAdapter = new GroupingAdapter(getActivity());
        
        ImageCacheParams cacheParams = new ImageCacheParams(IMAGE_CACHE_DIR);

        // Allocate a third of the per-app memory limit to the bitmap memory cache. This value
        // should be chosen carefully based on a number of factors. Refer to the corresponding
        // Android Training class for more discussion:
        // http://developer.android.com/training/displaying-bitmaps/
        // In this case, we aren't using memory for much else other than this activity and the
        // ImageDetailActivity so a third lets us keep all our sample image thumbnails in memory
        // at once.
        cacheParams.memCacheSize = 1024 * 1024 * Utils.getMemoryClass(getActivity()) / 3;

        // The ImageWorker takes care of loading images into our ImageView children asynchronously
        mImageWorker = new ThumbnailImageLoader(getActivity(), mImageThumbSize, mImageThumbSize*72/110, Thumbnails.MINI_KIND);
        mImageWorker.setAdapter(mSourceProvider);
        mImageWorker.setLoadingImage(R.drawable.empty_photo);
        mImageWorker.setImageFadeIn(false);
        mImageWorker.setImageCache(ImageCache.findOrCreateCache(getActivity(), cacheParams));
        setHasOptionsMenu(true);
        ActionBar actionbar = ((SherlockFragmentActivity)getActivity()).getSupportActionBar();
        actionbar.setDisplayHomeAsUpEnabled(false);
    }

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View v = inflater.inflate(R.layout.group_grid_fragment, container, false);
        mGridView = (GridView) v.findViewById(R.id.gridView);
        mGridView.setAdapter(mAdapter);
	    mGridView.setOnItemClickListener(FavouriteGridFragment.this);
	    mGridView.setOnItemLongClickListener(FavouriteGridFragment.this);
        // This listener is used to get the final width of the GridView and then calculate the
        // number of columns and the width of each column. The width of each column is variable
        // as the GridView has stretchMode=columnWidth. The column width is used to set the height
        // of each view so we get nice square thumbnails.
        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (mAdapter.getNumColumns() == 0) {
                            final int numColumns = (int) Math.floor(
                                    mGridView.getWidth() / (mFolderThumbSize + mFolderThumbSpacing));
                            if (numColumns > 0) {
                                final int columnWidth =
                                        (mGridView.getWidth() / numColumns) - mFolderThumbSpacing;
                                mAdapter.setNumColumns(numColumns);
                                mAdapter.setItemHeight(columnWidth*72/110 + getResources().getDimensionPixelSize(R.dimen.folder_thumbnail_text));
                                if (BuildConfig.DEBUG) {
                                    Log.d(TAG, "onCreateView - numColumns set to " + numColumns);
                                }
                            }
                        }
                    }
                });

        return v;
    }
    
    
    @Override
    public void onResume() {
        super.onResume();
        mSourceProvider.initSource();
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//    	final ImageCache cache = mImageWorker.getImageCache();
//        if (cache != null) {
//            mImageWorker.getImageCache().clearCaches();
////            DiskLruCache.clearCache(getActivity(), ImageFetcher.HTTP_CACHE_DIR);
//////            Toast.makeText(getActivity(), R.string.clear_cache_complete,
//////                    Toast.LENGTH_SHORT).show();
//        }
    	final Intent i;
    	if (position != mSourceProvider.getSize()-1){
    		i = new Intent(getActivity(), ImageGridActivity.class);
            i.putExtra(GlobalConst.INTENT_BUCKET_ID,  mSourceProvider.getItem(position).toString());
            i.putExtra(GlobalConst.INTENT_GROUP_TYPE, GlobalConst.INTENT_GROUP_TYPE_FAVOURITE);
            i.putExtra(GlobalConst.INTENT_MENU_TYPE, GlobalConst.MenuType.MENU_TYPE_ADDIMAGE);
            i.putExtra(GlobalConst.INTENT_BUCKET_NAME, mSourceProvider.getFolderList().get(position).getName());
            startActivity(i);
    	} else {
//    		i = new Intent(getActivity(), AddFavouriteActivity.class);
//	        startActivityForResult(i, 0);
    		final EditText albumName = new EditText(getActivity());
    		albumName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle(R.string.lable_addfavourite).setView(albumName)
			.setPositiveButton(R.string.button_addfavourite, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					String name = albumName.getText().toString();
					FavouriteDBHelper dbHelper = new FavouriteDBHelper(getActivity(), TableConstants.TABLE_FAVOURITE);
					try{
						if (dbHelper.isExist(TableConstants.FavouriteColumn.NAME, name))
							Toast.makeText(getActivity(), String.format(getString(R.string.toast_Fav_exist), name), Toast.LENGTH_SHORT).show();
						else {
							long id = dbHelper.insert(name);
							mSourceProvider.addFolderData(new FolderData(String.valueOf(id), name));
						}
					} catch(Exception e){
						
					} finally{
						dbHelper.closeDB();
					}
				}

			}).setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}

			}).show();
    	}
    }

    /**
     * The main adapter that backs the GridView. This is fairly standard except the number of
     * columns in the GridView is used to create a fake top row of empty views as we use a
     * transparent ActionBar and don't want the real top row of images to start off covered by it.
     */
    private class GroupingAdapter extends BaseAdapter {

        private final Context mContext;
        private int mItemHeight = 0;
        private int mNumColumns = 0;
        private int mActionBarHeight = -1;
        private GridView.LayoutParams mFolderViewLayoutParams;

        public GroupingAdapter(Context context) {
            super();
            mContext = context;
            mFolderViewLayoutParams = new GridView.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        }

        @Override
        public int getCount() {
            // Size of adapter + number of columns for top empty row
            return mSourceProvider.getFolderList().size();
        }

        @Override
        public Object getItem(int position) {
        	return mSourceProvider.getItem(position);
        }

        @Override
        public long getItemId(int position) {
        	return position;
        }

        @Override
        public int getViewTypeCount() {
            // Two types of views, the normal ImageView and the top row of empty views
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
        	return 0;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup container) {
        	
            final View view;
            
            ImageView imageView;
            ImageView borderView;
            TextView textView;
            //ImageView delView;
            if (convertView == null) { // if it's not recycled, instantiate and initialize
            	view = FavouriteGridFragment.this.getLayoutInflater(getArguments()).inflate(R.layout.groupgrid, null);
            	view.setLayoutParams(mFolderViewLayoutParams);
            	
                imageView = (ImageView)view.findViewById(R.id.folderimages);
                borderView = (ImageView)view.findViewById(R.id.albumborder);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                borderView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                textView = (TextView) view.findViewById(R.id.foldername);
                //delView = (ImageView) view.findViewById(R.id.delfolder);
            } else { // Otherwise re-use the converted view
            	view = convertView;
            	imageView = (ImageView)convertView.findViewById(R.id.folderimages);
            	borderView = (ImageView)convertView.findViewById(R.id.albumborder);
            	textView = (TextView)convertView.findViewById(R.id.foldername);
            	//delView = (ImageView)convertView.findViewById(R.id.delfolder);
            }
            // Check the height matches our calculated column width
            if (view.getLayoutParams().height != mItemHeight) {
            	view.setLayoutParams(mFolderViewLayoutParams);
            }
//            delView.setOnClickListener(new OnClickListener() {
//				
//				@Override
//				public void onClick(View v) {
//					Animation animation = AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out);
//					view.startAnimation(animation);
//					mDeletedFavs.add(getItem(position).toString());
//					animation.setAnimationListener(new AnimationListener() {
//						
//						@Override
//						public void onAnimationStart(Animation animation) {
//							// TODO Auto-generated method stub
//							
//						}
//						
//						@Override
//						public void onAnimationRepeat(Animation animation) {
//							// TODO Auto-generated method stub
//							
//						}
//						
//						@Override
//						public void onAnimationEnd(Animation animation) {
//							mSourceProvider.removeFolderData(position);
//							mAdapter.notifyDataSetChanged();
//						}
//					});
//				}
//			});

            // Finally load the image asynchronously into the ImageView, this also takes care of
            // setting a placeholder image while the background thread runs
//            mImageWorker.loadText(position, textView);
            
            if (position == mSourceProvider.getSize()-1)
            {
            	textView.setText("");
            	imageView.setImageResource(R.drawable.addalbum);
            }
            else{
            textView.setText(mSourceProvider.getFolderList().get(position).getName() + " (" 
            		+ mSourceProvider.getFolderList().get(position).getCount() + ")");
            mImageWorker.loadImage(position, imageView);
            }
            return view;
        }

        /**
         * Sets the item height. Useful for when we know the column width so the height can be set
         * to match.
         *
         * @param height
         */
        public void setItemHeight(int height) {
            if (height == mItemHeight) {
                return;
            }
            mItemHeight = height;
            mFolderViewLayoutParams =
                    new GridView.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
            mImageWorker.setImageSize(height);
            notifyDataSetChanged();
        }

        public void setNumColumns(int numColumns) {
            mNumColumns = numColumns;
        }

        public int getNumColumns() {
            return mNumColumns;
        }
    }

	@Override
	public void onDestroyView() {
		final ImageCache cache = mImageWorker.getImageCache();
        if (cache != null) {
            mImageWorker.getImageCache().clearCaches();
//            DiskLruCache.clearCache(getActivity(), ImageFetcher.HTTP_CACHE_DIR);
////            Toast.makeText(getActivity(), R.string.clear_cache_complete,
////                    Toast.LENGTH_SHORT).show();
        }
		super.onDestroyView();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//		if (mSourceProvider != null && mSourceProvider.getSize() > 0){
			SubMenu sub = menu.addSubMenu(Menu.NONE, 9093292, 1, "Settings");
			sub.setIcon(R.drawable.settings_button);
	        sub.add(Menu.NONE, R.id.settings_button, 0, getString(R.string.settings_account));
	        sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//	        menu.add(Menu.NONE, R.id.add_fav_button, 0, getString(R.string.lable_addfavourite));
//		} else
//			inflater.inflate(R.menu.menu1, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch(item.getItemId()){
			case android.R.id.home:
//				if (getActivity() instanceof SlidingFragmentActivity){
//					((SlidingFragmentActivity)getActivity()).getSlidingMenu().showBehind();
//				} else
//					getActivity().finish();
				break;
			case R.id.add_fav_button:
				final Intent i = new Intent(getActivity(), AddFavouriteActivity.class);
		        startActivityForResult(i, 0);
				break;
			case R.id.settings_button:
				final Intent i1 = new Intent(getActivity(), UserAccountActivity.class);
				startActivity(i1);
				break;
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}

//	private void showDelIcon() {
//		for (int i=0; i<mGridView.getChildCount(); i++){
//			mGridView.getChildAt(i).findViewById(R.id.delfolder).setVisibility(View.VISIBLE);
//		}
//	}
//	
//	

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode){
			case Activity.RESULT_OK:
				mSourceProvider.addFolderData(new FolderData(String.valueOf(data.getIntExtra(GlobalConst.INTENT_FAVOURITE_ID, -1)), data.getStringExtra(GlobalConst.INTENT_FAVOURITE_NAME)));
				break;
			default:
				break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, final View arg1, final int arg2,
			long arg3) {
		if (arg2 != mSourceProvider.getSize()-1){
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle(R.string.dialog_deleteAlbum).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Animation animation = AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out);
					arg1.startAnimation(animation);
					mDeletedFavs = new ArrayList<String>();
					mDeletedFavs.add(mSourceProvider.getItem(arg2).toString());
					animation.setAnimationListener(new AnimationListener() {
						
						@Override
						public void onAnimationStart(Animation animation) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void onAnimationRepeat(Animation animation) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void onAnimationEnd(Animation animation) {
							mSourceProvider.removeFolderData(arg2);
							mAdapter.notifyDataSetChanged();
							FavouriteDBHelper dbHelper = new FavouriteDBHelper(getActivity(), TableConstants.TABLE_FAVOURITE);
							FavouriteImagesDBHelper helper = new FavouriteImagesDBHelper(getActivity(), TableConstants.TABLE_FAVOURITE_IMAGES);
							try{
								dbHelper.delete(Integer.parseInt(mDeletedFavs.get(0)));
								dbHelper.closeDB();
								helper.delete(Integer.parseInt(mDeletedFavs.get(0)));
							}catch (Exception e){
								
							}finally{
								dbHelper.closeDB();
								helper.closeDB();
							}
							mDeletedFavs.clear();
						}
					});
					
				}

			}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}

			}).show();
		}
		return false;
	}
	
}

